package cn.bdqn.dao;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {



    //获取连接
    public Connection getConn(){
        Connection connection=null;
        try{
            Context context=new InitialContext();
            DataSource dataSource=(DataSource) context.lookup("java:comp/env/jdbc/news");
            connection=dataSource.getConnection();
        }catch (Exception e){
            e.printStackTrace();
        }
        return connection;
    }
    //关闭资源,里氏替换原则
    public void closeAll(ResultSet rs, Statement statement,Connection connnection){
        try {
            if(null!=rs){
                rs.close();
            }
            if(null!=statement){
                statement.close();
            }
            if(null!=connnection){
                connnection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //增删改
    public int upd(String sql,Object... objs){
        int count=0;
        PreparedStatement preparedStatement=null;
        Connection connection=null;
        try{
           connection= getConn();
           preparedStatement=connection.prepareStatement(sql);
            if(null!=objs){
                for (int i = 0; i <objs.length ; i++) {
                    preparedStatement.setObject(i+1,objs[i]);
                }
            }
            count=preparedStatement.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll(null,preparedStatement,connection);
        }

        return count;

    }
}
